package com.cn.algorithm02.class02;

import com.cn.algorithm02.class01.CodeUtil;

import java.util.Arrays;

/**
 * 二分法查找是否存在，首先保证有序
 */
public class C04_HalfExist {
    static int val = -3;
    public static void main(String[] args) {
        int tryNum = 10000;
        for (int i = 0; i < tryNum; i++) {
            int[] arr = CodeUtil.generatorArray(false);
            Arrays.sort(arr);

            int index = process(arr);
            if (!test(arr, index)) {
                for (int j : arr) {
                    System.out.printf(j + " ");
                }
                System.out.println("有问题");
            }

        }

        System.out.println("code is right");


        /*int[] arr = CodeUtil.generatorArray(false);
        arr[1] = val;
        Arrays.sort(arr);
        for (int i: arr) {
            System.out.printf(i + " ");
        }

        System.out.println("下标是： ");

        // System.out.println(process(arr, 0, arr.length - 1));
        System.out.println(process(arr));*/

    }

    public static int process(int[] arr) {
        int i = -1;
        if (arr == null) return i;
        int L = 0;
        int R = arr.length -1;

        while(L < R) {
            int mid = L + ((R-L)>>1); //防止l+r溢出
            if (arr[mid] < val) {
                L = mid + 1;
            } else if (arr[mid] == val){
                //System.out.println("mid1---");
                return mid; // 当while循环中时，也是整个跳出当前方法
            } else if (arr[mid] > val) {
                R = mid - 1;
            }
        }

        return arr[L] == val ? L : i ;
    }

    public static int process(int[] arr, int L, int R) {
        if (arr == null || L > R) return -1;

        int mid = L + ((R - L)>>1);
        if (arr[mid] < val) {
            L = mid + 1;
        } else if (arr[mid] > val) {
            R = mid - 1;
        } else {
            return mid;
        }

        return process(arr, L, R);
    }

    // 对数器
    public static boolean test(int[] arr, int index) {
        boolean b = false;
        if (index != -1) {
            return arr[index] == val ? true : false;
        } else {
            for (int i = 0; i < arr.length - 1; i++) {
                if (arr[i] == val) {
                    return false;
                }
            }
            return true;
        }
    }
}
